package com.ddwl.common.config;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.ddwl.common.constant.BaseEnum;
import com.ddwl.common.exception.GlobalException;
import com.ddwl.schema.vo.base.RestVo;
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.Response;
import feign.codec.Decoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.*;
import java.util.zip.GZIPInputStream;

/**
 * 类FeignConfig.java的实现描述：feign全局配置
 *
 * @author zach
 * @Date :2020-05-26 16:26.
 */
@Configuration
public class FeignConfig {

    @Bean
    public Decoder jsonDecoder(){
        return (Response response, Type type)->{
            InputStream inputStream = response.body().asInputStream();
            Map<String, Collection<String>> headerNames = response.headers();
            //解决GZIP压缩的问题
            if (headerNames != null) {
                Collection<String> values = headerNames.get("content-encoding");
                if(values!=null){
                    Iterator<String> iterator = values.iterator();
                    while (iterator.hasNext()){
                        if("gzip".equals(iterator.next())){
                            inputStream = new GZIPInputStream(inputStream);
                        }
                    }
                }
            }
            String body = IoUtil.read(inputStream,Charset.forName("UTF-8"));
            Object o = JSONObject.parseObject(body,type, Feature.OrderedField);
            if(o instanceof RestVo){
                if(((RestVo) o).getCode() != 200){
                    throw new GlobalException(((RestVo) o).getCode(),((RestVo) o).getMsg());
                }
            }
            return o;
        };
    }

    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.BASIC;
    }

    @Bean
    public RequestInterceptor headerInterceptor() {
        return (RequestTemplate requestTemplate) -> {

            requestTemplate.header("pk", BaseEnum.ProductEnum.API.getName());
            requestTemplate.header("pt", "server");
            requestTemplate.header("dk", UUID.randomUUID().toString());
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if(attributes == null) {
                return;
            }
            HttpServletRequest request = attributes.getRequest();
            if(request == null) {
                return;
            }
            Enumeration<String> headerNames = request.getHeaderNames();
//            requestTemplate.header("Content-Type", "application/json; charset=UTF-8");
            if (headerNames != null) {
                while (headerNames.hasMoreElements()) {
                    String name = headerNames.nextElement();
                    String values = request.getHeader(name);
                    // 跳过 content-length
                    if (name.equals("content-length")){
                        continue;
                    }
                    requestTemplate.header(name, values);
                }
            }
        };
    }
}
